class Game extends Subscriber{
  constructor(mapWidth, mapHeight, el, render, bgSpeed = 0.2) {
    super();
    this.mapWidth = mapWidth;
    this.mapHeight = mapHeight;
    this.player = null; // 玩家
    this.monster = null; // 怪兽
    this.el = el;
    this.render = render
    this.bgSpeed = bgSpeed
    // this.temp = null
  }
  init() {
    // 按理应该随机分配位置，这里省略了，简化一下逻辑
    const player = new Player({
      name: 'player', 
      x: 0, 
      y: 0, 
      width: 40, 
      height: 40,
      game: this,
      hp: PLAYER_INIT_HP,
      speed: PLAYER_MOVING_STEP
    });
    const monster = new Monster({
      name: 'monster', 
      x: this.mapWidth,
      y: this.mapHeight,
      width: 80, 
      height: 80,
      game: this,
      hp: 10000,
      speed: MONSTER_MOVING_STEP
    });

    this.player = player
    .on('move', ({x, y}) => {
      // 碰撞检测，玩家碰到怪物了扣除相应的hp
      if(!monster.collisionDetection(player.rect)){
        player.hp += HP_INCREASED_BY.MONSTER
      }
      monster.projectiles.forEach(bullet => {
        // 碰撞检测，玩家碰到子弹了扣除相应的hp
        if(!bullet.collisionDetection(player.rect)) {
          player.hp += HP_INCREASED_BY.BULLET
        }
      })
    })
    .on('bulletMove', bullet => {
      // 碰撞检测，子弹击中怪兽了扣除相应的hp
      if(!monster.collisionDetection(bullet.rect)) {
        monster.hp -= 300
        bullet.release()
        player.removeProjectile(bullet)
      }
    })
    .on('harmed', () => {
      let percent = player.hpPercent
      if(percent < 50 && percent > 30) {
        this.bgSpeed = 1
      }else {
        this.bgSpeed = 2
      }
    })
    .on('dead', e => {
      this.bgSpeed = 0
      alert('game over');
      this.monster.stop();
    })

    this.monster = monster
    .on('move', ({x, y}) => {
      // 碰撞检测，怪物碰到玩家了扣除相应的hp
      if(!player.collisionDetection(monster.rect)) {
        player.hp += HP_INCREASED_BY.MONSTER
      }
    })
    .on('bulletMove', bullet => {
      // 碰撞检测，子弹击中玩家了扣除相应的hp
      if(!player.collisionDetection(bullet.rect)) {
        player.hp += HP_INCREASED_BY.BULLET
        bullet.release()
        monster.removeProjectile(bullet)
      }
    })
    .on('dead', e => {
      this.bgSpeed = 0
      alert('you win!');
      this.monster.stop();
    })
    this.render(this, this.el);
  }
}

